package circuit_breaker

import (
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/circuitbreaker"
	"github.com/alibaba/sentinel-golang/core/config"
	"github.com/alibaba/sentinel-golang/core/flow"
	"github.com/alibaba/sentinel-golang/logging"
	"log"
)

// InitSentinel 初始化熔断器
func InitSentinel() {
	// We should initialize Sentinel first.
	conf := config.NewDefaultConfig()
	// for testing, logging output to console
	conf.Sentinel.Log.Logger = logging.NewConsoleLogger()
	err := sentinel.InitWithConfig(conf)
	if err != nil {
		log.Fatal(err)
	}
}

// InitSentinelLimitFlowRule 限流规则，基于QPS对某个资源限流
// threshold: 流控阈值
// StatIntervalInMs: 规则对应的流量控制器的独立统计结构的统计周期。如果StatIntervalInMs是1000，也就是统计QPS。
func InitSentinelLimitFlowRule(resourceName string, threshold float64, interval uint32) {
	_, err := flow.LoadRules([]*flow.Rule{
		{
			Resource:               resourceName,
			Threshold:              threshold,
			StatIntervalInMs:       interval,
			TokenCalculateStrategy: flow.Direct,
			ControlBehavior:        flow.Reject,
		},
	})
	if err != nil {
		fmt.Printf("规则配置失败 => 【%+v】 \n", err)
	}
}

// InitSentinelCbFlowRule 熔断规则
// threshold: 流控阈值
// StatIntervalInMs: 规则对应的流量控制器的独立统计结构的统计周期。如果StatIntervalInMs是1000，也就是统计QPS。
func InitSentinelCbFlowRule(rules []*circuitbreaker.Rule) {
	_, err := circuitbreaker.LoadRules(rules)
	if err != nil {
		fmt.Printf("规则配置失败 => 【%+v】 \n", err)
	}
}
